import { memo, useCallback } from 'react';
import { Panel, Table, TableSelectionModel } from '../../../../functionalComponent';
import { cssVar, Layout, iup } from '../../../../util';
import { OrgTree } from '../../../org-tree';
import { QueryPanel } from '../../../query-panel';
import { getTreeList, loadSourceData } from '../../service';
import { loopTreeChildren } from '../../utils';
import NoticeIconContent from './NoticeIconContent';
/**
 * 左树右表
 *
 */
const TreeTable = (props: any) => {
  const {
    getRef,
    state,
    popupMode,
    flowCode,
    busData,
    dependentState,
    changeDependent,
    rowDisable,
    iconVisible,
    onDataLoad
  } = props;

  // 表数据data
  const tableRequest = useCallback(
    (defaultParams) => {
      if (!dependentState) {
        return Promise.resolve({ total: 0, list: [] });
      }
      const sourceId = state.sourceId;
      const newsourceId = sourceId?.indexOf('_') ? iup.split(sourceId, '_')[1] : sourceId;
      return loadSourceData({
        flowCode,
        busData,
        ...defaultParams,
        popupMode,
        sourceId: newsourceId,
        treeFilterValue: dependentState
      });
    },
    [dependentState]
  );

  // tree数据data
  const treeRequest = useCallback(() => {
    return getTreeList(state?.treeFieldConfig);
  }, [JSON.stringify(state.treeFieldConfig)]);

  // 搜索框
  const onSearch = (_, queryCondition) => {
    getRef('table')?.current?.getApi().setExtraParam({ queryCondition });
  };

  // 搜索树
  const onSelectedChange = (_, record) => {
    const selectIds: string[] = loopTreeChildren(record) || [];
    changeDependent(selectIds.join(','));
  };

  return (
    <Layout.Flex direction="row" style={{ height: '100%' }}>
      <Layout.Slider size={200} style={{ marginRight: 'var(--inner-margin, 16px)', borderRight: cssVar.border }}>
        <Panel title={state?.treeFieldConfig?.title || '树'} autoFit />
        <OrgTree onSelectedChange={onSelectedChange} treeRequest={treeRequest} />
      </Layout.Slider>
      {/* 查询条件 */}
      <Layout.Flex direction="column">
        {state.queryItems.length > 0 && <QueryPanel items={state.queryItems} onSearch={onSearch} />}
        <NoticeIconContent iconVisible={iconVisible}>
          <Table
            showRowNumber
            columns={state.columns}
            ref={getRef('table')}
            autoLoad={true}
            request={tableRequest}
            key={state.sourceId}
            pagination={{ hideOnSinglePage: false }}
            rowSelection={{
              type:
                state.allowMultiSelect == 1
                  ? [TableSelectionModel.MULTIPLE_INTERVAL, TableSelectionModel.CHECKBOX]
                  : TableSelectionModel.ROW,
              disabled: rowDisable
            }}
            onDataLoad={onDataLoad}
          />
        </NoticeIconContent>
      </Layout.Flex>
    </Layout.Flex>
  );
};

export default memo(TreeTable);
